//
//  WebConnetionArray.m
//  Growth
//
//  Created by  on 12-2-9.
//  Copyright (c) 2012年 MEETStudio. All rights reserved.
//

#import "WebConnetionArray.h"
#import "PublicDatabaseEngine.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"


@interface WebConnectionArray (Private)

- (void)connectionFinished:(NSDictionary *)feedDictionary;

- (void)connectionError:(NSError *)error;

@end


@implementation WebConnectionArray

@synthesize connectionDelegate;
@synthesize jsonData;

@synthesize dataBaseListName;

@synthesize connectionURL;

- (id)initWith:(NSMutableURLRequest *)request delegate:(id)delegate dataBaseListName:(NSString *)listName{
	self.connectionDelegate = delegate;
    
    
    //数据缓存类型
    self.dataBaseListName=listName;
    
	
	[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	
	
	jsonData = [[NSMutableData data] retain];
	return self;
}

- (NSDictionary *)parseJSON:(NSMutableData *)data {
	CLog(@"Parsing JSON");
	NSError *error = nil;
    NSString *string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
  
    [self saveDataToDatabaseWithType:self.dataBaseListName  stringData:string];
  
    NSString *str=[NSString stringWithFormat:@"{\"object\":%@}",string];
    
    NSData *dat=[str dataUsingEncoding: NSUTF8StringEncoding];
	NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:dat error:&error];
	//CLog(@"connection data dict %@",dictionary);
	
	return dictionary;
}

// NSURLConnection Delegate Methods. You would want to include more for error handling //
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
   	self.connectionURL = [NSString stringWithFormat:@"%@",response.URL];
    
    NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
    
    
     statusCode = [httpResponse  statusCode ];
    
        
    NSLog ( @"status code = %d" ,statusCode);
   
    
    if  (statusCode !=  200 ){//网络错误
        
        CLog(@"网络%d错误",statusCode);
        
         NSError *error=nil;
        
        [self connectionArrayFaild:error  connectionURL:self.connectionURL];
        
    }
    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data {
	CLog(@"Recieving Data...");
	// Append the incomming data as it is received
	[jsonData appendData:data];
	NSString *stringData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
	//CLog(@"connection data %@",jsonData);
	CLog(@"connection data encode %@",stringData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	
	CLog(@"connection error: %@", error);

	[self connectionArrayFaild:error  connectionURL:self.connectionURL];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	CLog(@"Fininshed Loading...");
    
     if  (statusCode ==  200 ){    
	NSDictionary * feedDictionary = [self parseJSON:jsonData];
    
	[self connectionFinished:feedDictionary  connectionURL:self.connectionURL ];
	
	CLog(@"JSON as NSDictionary:: %@", feedDictionary);
         
     }
         
}


-(void)dealloc{
    
   
    [self.connectionURL release];
    [self.dataBaseListName release];
    [self.jsonData release];
    
     [super dealloc];
}

#pragma mark -Delegate
- (void)connectionFinished:(NSDictionary *)feedDictionary  connectionURL:(NSString *)url{
	
	if (connectionDelegate != nil) {
        
        if ([connectionDelegate respondsToSelector:@selector(connectionArraySuccess:connectionURL:)]) {
            [connectionDelegate connectionArraySuccess:feedDictionary connectionURL:url];
        }
	}
       
}




- (void)connectionArrayFaild:(NSError *)error connectionURL:(NSString *)url{
	
    CLog(@"connectionArrayFaild Error %@", error);
    
	if (connectionDelegate != nil) {
//        //NSString *domain = [error domain];
//        NSInteger errorCode = [error code];
//        //NSString *localizedDescription = [error localizedDescription];
//        
//        CLog(@"Error code %d", errorCode);
//        
//        if (errorCode == -1001) {
//            [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求超时，请检查网络状态！" duration:DEFAULT_LOADING_TIME];
//        }
//        else {
//            [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误，请检查网络状态！" duration:DEFAULT_LOADING_TIME];
//        }
        
        if ([connectionDelegate respondsToSelector:@selector(connectionArrayError:)]) {
            [connectionDelegate connectionArrayError:error];
        }
        if ([connectionDelegate respondsToSelector:@selector(connectionArrayError:connectionURL:)]) {
            CLog(@"connectionArrayFaild Error userinfo %@", [error userInfo]);
            NSDictionary *dict = [error userInfo];
            NSString *urlStr = [dict objectForKey:NSErrorFailingURLStringKey];
            [connectionDelegate connectionArrayError:error connectionURL:urlStr];
        }
		
	}
    
}

#pragma mark -save data to database
-(void)saveDataToDatabaseWithType:(NSString *)listType stringData:(NSString *)stringData{
    
    if (listType == nil) {
        return;
    }
    
    
    PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
       
     
    int userId = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
    
       
    
    //可管理的时间轴数据
    if ([listType isEqualToString:@"TimelineId"]) {
        
        NSString *sql = [NSString stringWithFormat:@"insert or replace into TimelineId (uid,json) values (%d, '%@');", userId,stringData];
        
        CLog(@"timeline member stringData %@", stringData);
        
        BOOL isSuccess;
        isSuccess = NO;
        while (!isSuccess) {
            isSuccess = [databaseEngine executeSQL:sql];
        }
        
        
    }

          
}





@end
